package com.wl.jetpackdemo.base.network

import com.wl.wllite.net.BaseResponse
import com.wl.wllite.net.exception.ErrorStatus
import com.wl.wllite.net.exception.ExceptionHandle
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

/**
 * 不用协程直接用retrofit的时候封装的回调类
 *
 * Created by wangliang on 2021/1/27.
 */
abstract class CommonCallback<T>: Callback<BaseResponse<T>> {
    override fun onResponse(call: Call<BaseResponse<T>>, response: Response<BaseResponse<T>>) {
        if(response.isSuccessful) {
            if(response.body() != null) {
                if(response.body()?.code == ErrorStatus.SUCCESS) {
                    onSucc(response.body()?.data)
                } else {
                    onError(response.body()?.code, response.body()?.msg)
                }
            } else {
                onError(ErrorStatus.RESP_EMPTY_ERROR, "接口返回数据为空")
            }
        } else {
            onError(response.code(), "服务器错误(" + response.code() + ")")
        }
    }

    override fun onFailure(call: Call<BaseResponse<T>>, t: Throwable) {
        ExceptionHandle.handleException(t)
        onError(ExceptionHandle.errorCode, ExceptionHandle.errorMsg)
    }


    abstract fun onSucc(t: T?)

    abstract fun onError(code: Int?, message: String?)
}